package com.usian.category.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.category.dao.CategoryDao;
import com.usian.category.pojo.Category;
import com.usian.category.pojo.ResultVo;
import com.usian.category.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category>implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /*
    *1.从redis获取数据
    * 2.如果有，直接返回
    * 3.如果没有，查数据库，然后将数据库中的数据存到redis中
    *
    * */
    @Override
    public /*synchronized*/ ResultVo showList() {
        String redisJson = stringRedisTemplate.opsForValue().get("category");
        if (StrUtil.isEmpty(redisJson)){
            System.out.println("redis没有数据，查询数据库");
            List<Category>list=showListFromDb();
            stringRedisTemplate.opsForValue().set("category",JSON.toJSONString(list));
            return new ResultVo(200,"success",list);
        }
        System.out.println("redis有数据，直接返回");
        List<Category>list=JSON.parseArray(redisJson,Category.class);
        return new ResultVo(200,"success",list);
    }
    public List<Category> showListFromDb() {
        List<Category> list=categoryDao.selectList(null);
        List<Category>levelOne=list.stream().filter((res)->{
            return res.getParentCid()==0;
        }).map((category)->{
            category.setChildren(showChild(list,category.getCatId()));
            return category;
        }).collect(Collectors.toList());
        return levelOne;
    }

    private List<Category> showChild(List<Category> list, int catId) {
        List<Category>list1=list.stream().filter((category) -> {
            return category.getParentCid() == catId;
        }).map((res)->{
            res.setChildren(showChild(list,res.getCatId()));
            return res;
        }).collect(Collectors.toList());
        return list1;
    }




    @Override
    public ResultVo tree() {
        return null;
    }
}










